#!/bin/bash
# 设置基本信息
timestamp="$(date +%Y%m%d%H%M)"
branch=${GIT_LOCAL_BRANCH:-$(git rev-parse --abbrev-ref HEAD)}
project_name=iot
repo_name=server-name
docker_reg=""
package_name=api

# 变量组设置
env_suffix="-test"
if [[ $branch =~ ^preview.* ]]; then
  env_suffix="-${branch}"
fi
if [ "$branch" = "master" ]; then
  env_suffix=""
fi

# 登录
docker login -u "$USERNAME" -p "$PASSWORD" $docker_reg

# 清空脚本
echo '' > k8s_deploy.sh

image_full_name="${repo_name}-${package_name}:${branch}-${timestamp}"

# 构建镜像
docker build -t "${image_full_name}" -f Dockerfile .

# 构建失败报错
if [ $? != 0 ]; then
exit 1
fi

# 更新镜像
docker tag "${image_full_name}" ${docker_reg}/"${image_full_name}"
#docker push ${docker_reg}/"${image_full_name}"

# 输出部署命令
k8s_namespace=${project_name}
for name in 'api'
do
k8s_set_name="${repo_name}-${name}${env_suffix}"
echo "
kubectl set image -n $k8s_namespace deployment/${k8s_set_name} ${k8s_set_name}=${docker_reg}/${image_full_name} --record
if [ \$? != 0 ]; then
exit 1
fi
" >> k8s_deploy.sh
done
